package ${beanPackage};

/**
 * @author: ${Author}
 * @date: ${DATE}
 */

import io.vertx.core.MultiMap;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import ldh.common.PageResult;
import org.apache.commons.lang3.StringUtils;
import java.util.Map;


public class JsonObjectUtil {

    public static JsonArray toJsonArray(JsonObject jsonObject, String... fields) {
        JsonArray jsonArray = new JsonArray();
        for (String field : fields) {
            Object value = jsonObject.getValue(field);
            if (value == null) {
                jsonArray.addNull();
            } else {
                jsonArray.add(value);
            }
        }
        return jsonArray;
    }

    public static String where(JsonObject jsonObject, String... fields) {
        StringBuilder sb = new StringBuilder();
        boolean haveWhere = false;
        for (String field : fields) {
            Object value = jsonObject.getValue(field);
            if (value != null) {
                sb.append(field).append("= ?").append(" and ");
                haveWhere = true;
            }
        }
        String where = sb.toString();
        if (haveWhere) where = where.substring(0, where.length() - 5);
        return where;
    }

    public static JsonArray whereParam(JsonObject jsonObject, String... fields) {
        JsonArray jsonArray = new JsonArray();
        for (String field : fields) {
            Object value = jsonObject.getValue(field);
            if (value != null) {
                jsonArray.add(value);
            }
        }
        return jsonArray;
    }

    public static String limit(JsonObject jsonObject) {
        Integer[] pageable = pageable(jsonObject);
        int pageNoi = pageable[0] - 1  < 0 ? 0 : (pageable[0] - 1) * pageable[1];
        String where = String.format(" limit %s, %s", pageNoi, pageable[1]);
        return where;
    }

    public static void pageable(PageResult pageResult, JsonObject jsonObject) {
        Integer[] pageable = pageable(jsonObject);
        pageResult.setPageSize(pageable[1]);
        pageResult.setPageNo(pageable[0]);
        pageResult.handlePage();
    }

    public static JsonObject toJsonObject(MultiMap map) {
        JsonObject jsonObject = new JsonObject();
        for (Map.Entry<String, String> entry : map.entries()) {
            jsonObject.put(entry.getKey(), entry.getValue());
        }
        return jsonObject;
    }

    private static Integer[] pageable(JsonObject jsonObject) {
        String pageSize = jsonObject.getString("pageSize");
        String pageNo = jsonObject.getString("pageNo");
        pageSize = StringUtils.isEmpty(pageSize) ? "10" : pageSize;
        pageNo = StringUtils.isEmpty(pageNo) ? "0" : pageNo;
        int pageNoi = Integer.parseInt(pageNo);
        int pageSizei = Integer.parseInt(pageSize);
        return new Integer[]{pageNoi, pageSizei};
    }
}
